package com.agw.crm.web.filter;

import com.agw.crm.settings.domain.User;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class LoginFilter implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {

        System.out.println("进入到有没有登录过服务器的验证");
        //获取到HttpServletRequest,HttpServletResponse对象（强转）
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        //在这里进行判断，不能拦截login.jsp和验证登录页面
        String servletPath = request.getServletPath();
        if ("/login.jsp".equals(servletPath) || "/settings/user/login.do".equals(servletPath)){
            chain.doFilter(req,resp);

            //除了上面那两个地址都要进行拦截
        }else {

            //获取到用户的session对象
            HttpSession session = request.getSession();
            //拿到session对象中的数据
            User user = (User) session.getAttribute("user");

            //判断user不为空，放行
            if (user != null){
                chain.doFilter(req,resp);
            }else {
                //为空则没登陆过，通过重定向，跳转到登录页
                response.sendRedirect(request.getContextPath() + "/login.jsp");

            }
        }

    }
}
